import pool from '../config/database.js';

export const ActivityModel = {
  async getAllActivities() {
    try {
      const [rows] = await pool.query('SELECT * FROM activities ORDER BY date, time');
      return rows;
    } catch (error) {
      console.error('Database error:', error);
      throw new Error('Failed to fetch activities');
    }
  },

  async createActivity(activity) {
    try {
      console.log('Creating activity with data:', activity);
      // 转换日期格式
      const date = activity.date.split('T')[0];
      const time = activity.time.substring(11, 16); // 提取HH:mm格式

      const [result] = await pool.query(
        'INSERT INTO activities (name, date, time, location, participants, status) VALUES (?, ?, ?, ?, ?, ?)',
        [activity.name, date, time, activity.location, activity.participants, activity.status]
      );
      return result.insertId;
    } catch (error) {
      console.error('Database error:', error);
      throw new Error('Failed to create activity');
    }
  },

  async updateActivity(id, activity) {
    try {
      console.log('Updating activity with data:', { id, activity });
      // 检查记录是否存在
      const [existing] = await pool.query('SELECT * FROM activities WHERE id = ?', [id]);
      if (!existing || existing.length === 0) {
        throw new Error(`Activity with id ${id} not found`);
      }

      // 如果只是更新状态（取消活动）
      if (Object.keys(activity).length === 1 && activity.status) {
        const [result] = await pool.query(
          'UPDATE activities SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
          [activity.status, id]
        );
        return result.affectedRows > 0;
      }

      // 转换日期格式
      const date = activity.date.split('T')[0];
      const time = activity.time.substring(11, 16); // 提取HH:mm格式

      const query = `
        UPDATE activities 
        SET name = ?, 
            date = ?, 
            time = ?, 
            location = ?, 
            participants = ?, 
            status = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `;
      
      const [result] = await pool.query(query, [
        activity.name,
        date,
        time,
        activity.location,
        activity.participants,
        activity.status,
        id
      ]);

      if (result.affectedRows === 0) {
        throw new Error('No records were updated');
      }

      return true;
    } catch (error) {
      console.error('Database error:', error);
      throw new Error(`Failed to update activity: ${error.message}`);
    }
  }
};